package server;



import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class Server {
	private ServerSocket serverSocket;
	private String name;
	private HashMap<String, Socket> clientList;
	
	public Server(String name){
		this.name = name;
		this.clientList = new HashMap<>();
	}
	
	public void create() throws IOException{
		serverSocket = new ServerSocket(1234);
	}
	
	public void close() throws IOException{
		if (serverSocket != null) serverSocket.close();
	}
	
	public void loop() throws IOException{
		Socket clientSocket = null;
		while (true) {
			clientSocket = serverSocket.accept();
			System.out.println("Mot client da ket noi den: " + clientSocket.getRemoteSocketAddress());
			
			new Thread(new ClientHandler(clientSocket, name, clientList)).start();
		}
		
	}

	public static void main(String[] args) {
		Server server = new Server("Server");
		try {
			server.create();
			System.out.println("Tao server thanh cong");
			server.loop();
		} catch (IOException e) {
			try {
				server.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}
}
